package com.example.app2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Activity_list extends AppCompatActivity implements Runnable {
    private static final String TAG = "";
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        ListView listView = findViewById(R.id.listview);
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 2) {
                    List<String> list2 = (List<String>) msg.obj;
                    ListAdapter adapt = new ArrayAdapter<String>(Activity_list.this, android.R.layout.simple_list_item_1, list2);
                    listView.setAdapter(adapt);
                }
                super.handleMessage(msg);
            }
        };

        Thread td = new Thread(this);
        td.start();


    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);                      //设置子线程的延迟时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Message msg = handler.obtainMessage(2);
        Document doc = null;
        List<String> list = new ArrayList<>();
        List<RateItem> list2 = new ArrayList<>();
        try {
            doc = Jsoup.connect(" https://www.boc.cn/sourcedb/whpj/").get();   //使用jsoup爬取网页上的数据，得到一个doc
            Elements tables = doc.getElementsByTag("table");                  // getElementsByTag 获得标签信息，返回一个Elements对象
            Element table = tables.get(1);
            Elements tds = table.getElementsByTag("td");
            for (int i = 0; i < tds.size(); i += 8) {
                Element coin = tds.get(i);
                Element getWebRate = tds.get(i + 5);
                list.add(coin.text() + ":" + getWebRate.text());

                RateItem r = new RateItem();
                r.getCurName();
                r.getCurRate();
                list2.add(r);
                DBManager m = new DBManager(Activity_list.this);
                m.addAll(list2);



                Log.i(TAG, "coin " + coin.text());
                Log.i(TAG, "getWebRate " + getWebRate.text());
            }
            msg.obj = list;
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

